// 导入依赖的模块
yepjs.require("jquery");
yepjs.require("YBA.Data.login");

/*
 * 一些验证函数
 */
yepjs.define("check", {

    NS: "YBA.Common",

    fields: {
        /*
         * 验证输入是否空值
         * @val:要验证的字符串
         */
        isNull: function (val) {
            return (val.replace(/\s+/g, "") === "");
        },
        /*
         * 验证输入是否是合法邮箱地址
         * @val:字符串
         */
        isEmail: function (val) {
            var p = /^\w+(?:[-+.']\w+)*@\w+(?:[-.]\w+)*\.\w+(?:[-.]\w+)*$/;
            return p.test(val);
        },
        /*
         * 密码复杂度验证
         * @val:字符串
         */
        isPwd: function (val) {
            var p = /^(?=.*?[a-zA-Z])(?=.*?[0-6])[!"#$%&'()*+,\-./:;<=>?@\[\\\]^_`{|}~A-Za-z0-9]{6,50}$/;
            return p.test(val);
        },
        /*
         * 验证输入是否是合法手机号
         * @val:字符串
         */
        isMobile: function (val) {
            var p = /^[1][358][0-9]{9}$/;
            return p.test(val);
        },
        /*
         * 字符串长度验证
         * @val:字符串
         * @long:字符串长度
         */
        isHowLong: function (val,long) {
            if(val.length>parseInt(long)){
                return true;
            }else{
                return false;
            }
        },
        /*
         * 验证输入是否是数字
         * @val:要验证的字符串或数字
         * @options:可选参数，{min:最小值,max:最大值,decimals:可以带几位小数}
         */
        isNum: function (val, options) {
            var options = options || {};
            var p = /^\d+(?:\.\d+)?$/;
            if(!val){
            	return true;
            }
            if (options.decimals) {
                p = new RegExp("^\\d+(?:\\.\\d{1," + options.decimals + "})?$");
            }else if(options.decimals === 0){
                p = /(^[1-9](\d+)?$)|(^[0]$)/;
            }
            var test = p.test(val);
            if (options.min) {
                if (parseFloat(val) < options.min) {
                    test = false;
                }
            }
            if (options.max) {
                if (parseFloat(val) > options.max) {
                    test = false;
                }
            }
            return test;
        },
        /*
         * 验证输入是否是合法IP地址
         * @val:字符串
         */
        isIP: function (val) {
            var p = /^(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[1-9])\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)$/;
            if (p.test(val)) { return true; } else { return false; }
        },
        /*
         * 验证输入是否是合法端口号
         * @val:字符串
         */
        isPort: function (val) {
            var p = /^([0-9]|[1-9]\d|[1-9]\d{2}|[1-9]\d{3}|[1-5]\d{4}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]\d|6553[0-5])$/;
            if (p.test(val)) { return true; } else { return false; }
        },
        /*
         * 验证输入是否是合法url地址
         * @val:字符串
         */
        isUrl: function (val) {
            var p = /^(?:http(?:s)?:\/\/)?([\w-]+\.)+[\w-]+(?:\/[\w- .\/\?%&=]*)?$/;
            if (p.test(val)) { return true; } else { return false; }
        }
    }
});

// 倒计时
yepjs.define("timer", {

    NS: "YBA.Common",

    field: function (time, onTicking, ended) {

        var time = time || {};
        var d = parseInt(time.d) || 0;
        var h = parseInt(time.h) || 0;
        var m = parseInt(time.m) || 0;
        var s = parseInt(time.s) || 0;
        s += d * 24 * 3600 + m * 60 + h * 3600;
        if (s == 0) { return false; }
        var ticker = 0;
        var isobj = time.format == "json" ? true : false;
        // 将秒转换成{d:天,h:时,m:分,s:秒}形式
        function convert2hms(s) {
            var d = Math.floor(s / (24 * 3600)); s -= d * 24 * 3600;
            var h = Math.floor(s / 3600); s -= h * 3600;
            var m = Math.floor(s / 60); s -= m * 60;
            return { d: d, h: h, m: m, s: s }
        }
        var i = setInterval(function () {
            s--;
            var cur = isobj == true ? convert2hms(s) : s;
            if (onTicking) { onTicking.call(i, cur); };
            if (s == 0) { clearInterval(i); if (ended) { ended.call(i, cur); } }
        }, 1000);
    }
});

/*
 * 使某个元素相对于浏览器窗口居中
 * @obj：jQuery对象
 */
yepjs.define("setCenter", {

    NS: "YBA.Common",

    field: (function () {

        var isIE6 = window.attachEvent && !window.XMLHttpRequest;

        return function (obj) {
            var $win = $(window);
            var st = $win.scrollTop();   //窗口高度
            var sl = $win.scrollLeft();  //窗口高度

            var h = $win.height();   //窗口高度
            var w = $win.width();    //窗口宽度

            var l_w = obj.innerWidth();  //元素宽度
            var l_h = obj.innerHeight(); //元素高度

            var top = (parseInt(h) - parseInt(l_h)) / 2;
            var left = (parseInt(w) - parseInt(l_w)) / 2 + sl;

            if (!isIE6) {
                obj.css({ top: top, left: left, position: "fixed" });
            } else {

                obj.css({ top: top + st, left: left, position: "absolute" });
            }
        };

    })()
});

/*
 * 解析查询字符串
 * @name:键值
 */
yepjs.define("queryString", {

    NS: "YBA.Common",

    field: (function () {

        var search = location.search, cache = {}, pattern = /([^?=&]+)=([^&#]*)/g;

        return function (name) {

            // 判断是否已经存在缓存
            // 如果是，则直接查找指定的name
            // 否则解析查询字符串，并将键值对保存到cache[name]
            if (!cache[name]) {
                while (pattern.exec(search)) {
                    cache[RegExp.$1] = RegExp.$2;
                }
            }
            return cache[name] || "";
        }

    })()
});

/*
 * 定义一个模板引擎
 * 示例：
 * var html = YBA.Common.ysmart(str, data);
 */
yepjs.define("ysmart", {

    NS: "YBA.Common",

    field: (function () {

        var 
        // 匹配逻辑语句的正则
            jsPattern = /^<@(.*?)@>$/,
        // 匹配嵌入变量的正则
            varPattern1 = /^<@\s*={1}\s*(.*?)@>$/,
        // 匹配嵌入变量的正则，不编码HTML标签
            varPattern2 = /^<@\s*={2}\s*(.*?)@>$/;

        // html编码
        var htmlEncode = function (str) {
            return str && str.toString().replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/\\/g, '&#92;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#39;');
        };

        var ysmart = function (html, data) {

            var htmlArr = [],
                code = "var r=[], DATA = this;\n";

            if (typeof html === "undefined") {
                throw new Error("参数错误，未传递html字符串");
            }

            // 将html和js语句分离到不同的行
            html = html.replace(/\r?\n/g, "").replace(/<@/g, "\n<@").replace(/@>/g, "@>\n");
            // 分离到数组
            htmlArr = html.split(/\r?\n/g);

            // 循环数组
            for(var index=0, len = htmlArr.length; index < len; index++){
                
                var item = htmlArr[index];
                
                // 是否匹配不进行html编码的变量
                if (varPattern2.test(item)) {
                    code += "r.push(" + RegExp.$1 + ");\n";
                }
                // 是否匹配需要进行html编码的变量
                else if (varPattern1.test(item)) {
                    code += "r.push(htmlEncode(" + RegExp.$1 + "));\n";
                }
                // 匹配逻辑语句
                else if (jsPattern.test(item)) {
                    code += RegExp.$1 + "\n";
                }
                // 否则识别为html字符串
                else if (item.replace(/\s/g, "") !== "") {
                    code += "r.push('" + item.replace(/\\/g, "\\\\").replace(/'/g, "\\'") + "');\n";
                }
            }

            code += "return r.join('');";
            
            return new Function("htmlEncode", code).call(data, htmlEncode);
        };

        return ysmart;
    })()
});

/*
 * 使元素可拖动
 * @start:鼠标按住的元素，Jquery对象
 * @move:要移动的元素，Jquery对象
 * @draging:回调函数，可选，移动中促发，传入当前移动的对象，该回调函数的上下文对象this将指向该对象
 * @dragend:回调函数，可选，移动结束后促发，传入当前移动的对象，该回调函数的上下文对象this将指向该对象
 */
yepjs.define("drag", {
    
    NS: "YBA.Common",
    
    field: function (start, move, draging, dragend) {
        
        var isIE6 = window.attachEvent && !window.XMLHttpRequest && navigator.userAgent.indexOf("MSIE 6.0") > -1;
        
        if ($.browser && $.browser.mozilla) {
            start.css("-moz-user-select", "none");
        } else {
            start.bind("selectstart", function () { return false; });
        }
        
        var moveElem = move ? move : start,
            win = $(window), body = $("body");
        
        start.mousedown(function (e) {
            if (e.button == 2) { return false; }
            var event = e || window.event;
            var left = event.clientX;
            var top = event.clientY;
            var oleft = move ? move.offset().left : start.offset().left;
            var otop = move ? move.offset().top : start.offset().top;
            var newleft = left - oleft;
            var newtop = top - otop;
            var position = isIE6 ? "absolute" : "fixed";
            var position = "absolute";
            
            body.bind("mousemove", startDrag);

            function startDrag(e) {
                event = e || window.event;
                left = event.clientX;
                top = event.clientY;
                
                if (!isIE6) {
                    var st = win.scrollTop();
                    var sl = win.scrollLeft();
                    moveElem.css({ position: position, left: (left - newleft - sl) + "px", top: (top - newtop - st) + "px" });
                } else {
                    moveElem.css({ position: position, left: (left - newleft) + "px", top: (top - newtop) + "px" });
                }
                
                moveElem.css({ position: position, left: (left - newleft) + "px", top: (top - newtop) + "px" });
                if (draging) { draging.call(moveElem); }
            }

            start.mouseup(function () {
                start.unbind("mouseup");
                body.unbind("mousemove", startDrag);
                if (dragend) { dragend.call(moveElem); }
            });
        }).mouseout(function (e) {
            var event = e || window.event;
            var left = event.clientX;
            var top = event.clientY;
            var oleft = move ? move.offset().left : start.offset().left;
            var otop = move ? move.offset().top : start.offset().top;
            var newleft = left - oleft;
            var newtop = top - otop;
            var position = isIE6 ? "absolute" : "fixed";
            var position = "absolute";
            
            left = event.clientX;
            top = event.clientY;
            
            if (!isIE6) {
                var st = win.scrollTop();
                var sl = win.scrollLeft();
                moveElem.css({ position: position, left: (left - newleft - sl) + "px", top: (top - newtop - st) + "px" });
            } else {
                moveElem.css({ position: position, left: (left - newleft) + "px", top: (top - newtop) + "px" });
            }
            moveElem.css({ position: position, left: (left - newleft) + "px", top: (top - newtop) + "px" });
        });
    }
});

/*
 * sidebar展开/关闭&&二级菜单展开关闭
 */

yepjs.define("sidebar", {

    NS: "YBA.Common",

    field: function() {
        var Tog = {
            // 初始化事件
            init: function() {
                for (var i in Tog.event) {
                    Tog.event[i]();
                }
            },
            // 页面元素
            el: {
                togglerBtn : $(".icos-toggler"),
                sidebar : $(".sidebar"),
                sidebarMenu : $(".sidebar-menu"),
                sMenuList : $("a.a-menu"),
                pageContent : $(".page-content")
            },
            // 初始化时执行的所有事件
            event: {
                sidebarTog:function(){
                    Tog.el.togglerBtn.click(function() {
                        if (Tog.el.togglerBtn.hasClass("toggler-close")) {
                            Tog.el.sidebar.animate({
                                width: "37px"
                            }, 100, function() {
                                Tog.el.pageContent.css("left", "37px");
                                Tog.el.sidebarMenu.css("display", "none");
                                Tog.el.togglerBtn.removeClass("toggler-close").addClass(("toggler-open"));
                                YBA.Common.autoWidth();
                            });
                        } else {
                            Tog.el.sidebar.animate({
                                width: "225px"
                            }, 100, function() {
                                Tog.el.pageContent.css("left", "225px");
                                Tog.el.sidebarMenu.css("display", "block");
                                Tog.el.togglerBtn.removeClass("toggler-open").addClass(("toggler-close"));
                                YBA.Common.autoWidth();
                            });
                        };
                    });
                },
                secondMenu:function(){
                    Tog.el.sMenuList.click(function() {
                        var that = $(this);
                        if (that.parents("li").hasClass("active")) {
                            that.siblings('ul.sub-menu').slideToggle();
                        } else {
                            Tog.el.sidebarMenu.find("li.active").children("ul.sub-menu").slideUp();
                            that.siblings('ul.sub-menu').slideToggle();
                            that.parents("li").addClass("active").siblings("li").removeClass('active');
                        }
                    });
                }
            }
        };

        Tog.init();
    }
});


/*
 ** 屏宽自适应变化
 */
yepjs.define("autoWidth", {

    NS: "YBA.Common",

    field: function () {
        var Auto = {
            // 初始化事件
            init: function() {
                for (var i in Auto.event) {
                    Auto.event[i]();
                }
            },
            // 页面元素
            el: {
                win : $(window),
                brandLong : $(".brand-title-long"),
                brandShort : $(".brand-title-short")
            },
            // 功能函数集合
            fn: {
                winResize : function(){
                    if(Auto.el.win.width() <= 1246){
                        Auto.el.brandLong.hide();
                        Auto.el.brandShort.show();
                    }else{
                        Auto.el.brandShort.hide();
                        Auto.el.brandLong.show();
                    }
                }
            },
            // 初始化时执行的所有事件
            event: {
                autoFn : function(){
                    Auto.fn.winResize();
                    Auto.el.win.resize(Auto.fn.winResize);
                }
            }
        }

        Auto.init();
    }
});

/*
 ** 表格适应变化
 */
yepjs.define("gridWidth", {

    NS: "YBA.Common",

    field: function () {
        var gridAuto = {
            // 初始化事件
            init: function() {
                for (var i in gridAuto.event) {
                    gridAuto.event[i]();
                }
            },
            // 页面元素
            el: {
                win : $(window),
                btns:$(".search-btns"),
                longBtns:$(".long-search-btns"),
                shortBtns:$(".short-search-btns"),
                tHead:$(".thead"),
                tBody:$(".tbody"),
                contArea:$(".cont-area"),
                gridToolbar:$(".grid-toolbar")

            },
            // 功能函数集合
            fn: {
                winResize : function(){
                    var offRight = gridAuto.el.win.width() - (gridAuto.el.btns.offset().left + gridAuto.el.longBtns.width());
                    if(offRight <= 13){
                        gridAuto.el.shortBtns.show();
                        gridAuto.el.longBtns.hide();
                    }else{
                        gridAuto.el.longBtns.show();
                        gridAuto.el.shortBtns.hide();
                    }
                    var thead_top = gridAuto.el.contArea.height() + gridAuto.el.gridToolbar.height() + 1;
                    var tbody_top = gridAuto.el.tHead.height() + thead_top;
                    gridAuto.el.tHead.css("top",thead_top+"px");
                    gridAuto.el.tBody.css("padding-top",tbody_top+"px");
                }
            },
            // 初始化时执行的所有事件
            event: {
                autoFn : function(){
                    gridAuto.fn.winResize();
                    gridAuto.el.win.resize(gridAuto.fn.winResize);
                }
            }
        }

        gridAuto.init();
    }
});

/*taps选项卡*/
yepjs.define("taps", {

    NS: "YBA.Common",

    field: function (options) {
        var card = options.con.find(".ui-taps-card li");
        var body = options.con.find(".ui-taps-body");
        card.bind("click", function() {
            var t = $(this);
            t.addClass('on').siblings(".ui-taps-card li").removeClass('on');
            body.eq(t.index()).addClass('active').siblings('.ui-taps-body').removeClass('active');
        });
    }
});

/*当前页面高亮*/
yepjs.define("menuActive", {

    NS: "YBA.Common",

    field: function () {
         var Biz = {
            // 初始化事件
            init: function() {
                for (var i in Biz.event) {
                    Biz.event[i]();
                }
            },
            //  公共变量
            vars: {
                url: window.location.pathname,
                dataHref: $(".sidebar-menu").attr("data-href")
            },
            // 页面元素
            el: {
                firstMenu:$(".nav li"),
                secondMenu:$(".sidebar-menu>li"),
                thirdMenu:$(".sub-menu li")
            },
            // 功能函数集合
            fn: {
                //遍历菜单
                ergodicMenu:function(callback){
                    var urlArr = Biz.vars.url.split("/");
                    callback(urlArr);
                }
            },
            // 初始化时执行的所有事件
            event: {
                //初始化菜单
                initMenu:function(){
                    Biz.fn.ergodicMenu(function(urlArr){
                    	var secondDom = Biz.el.secondMenu;
                    	var firstDom = Biz.el.firstMenu;
                    	for(var i = 0;i<secondDom.length; i++){
                            var liHref = secondDom.eq(i).children("a").attr("href");
                            if(urlArr[urlArr.length-1] == liHref){
                            	secondDom.removeClass("active");// 删除其他兄弟元素的样式
                            	secondDom.eq(i).addClass("active");// 添加当前元素的样式
                            }
                        }
                    	for(var i = 0;i<firstDom.length; i++){
                            var liHref = firstDom.eq(i).children("a").attr("href");
                            if(Biz.vars.dataHref == liHref || urlArr[urlArr.length-1] == liHref){
                            	firstDom.removeClass("active");// 删除其他兄弟元素的样式
                            	firstDom.eq(i).addClass("active");// 添加当前元素的样式
                            }
                        }  	
                    });
                    Biz.fn.ergodicMenu(function(urlArr){
                    	var dom = Biz.el.thirdMenu;
                    	for(var i = 0;i<dom.length; i++){
                            var liHref = dom.eq(i).children("a").attr("href");
                            if(urlArr[urlArr.length-1] == liHref){
                                dom.removeClass("on");// 删除其他兄弟元素的样式
                                dom.eq(i).addClass("on");// 添加当前元素的样式
                                dom.eq(i).parents("li").addClass("active");
                            }
                        }
                    });
                }
            }
        };

        Biz.init();

        return Biz;
    }
});

/*退出登录*/
yepjs.define("logout", {

    NS: "YBA.Common",

    field: function () {
        var jlogout = $(".j-logout");
        jlogout.bind('click', function() {
            var confirm = YBA.Plugin.confirm({
                msg: "您确定要退出吗？",
                btnTxt1: "确定",
                yes: function () {
                    confirm.hide();
                    YBA.Data.login.logout({},function(json){
                        if (json.code == 200) {
                            location.href = "login.jsp";
                        }else{
                            YBA.Plugin.msgtip({type: "i",msg: "操作失败"});
                        }
                    })
                }
            })
        });
    }
});




